package com.yangguang.huahui.ui.fragments;

import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.aigestudio.wheelpicker.core.AbstractWheelPicker;
import com.aigestudio.wheelpicker.widget.cross.CrossDatePicker;
import com.yangguang.huahui.Config;
import com.yangguang.huahui.R;
import com.yangguang.huahui.entity.BuyEditInfo;
import com.yangguang.huahui.entity.DataInfo;
import com.yangguang.huahui.entity.Guige;
import com.yangguang.huahui.entity.HttpResult;
import com.yangguang.huahui.entity.SelectEntity;
import com.yangguang.huahui.entity.Upload;
import com.yangguang.huahui.mvp.model.CommonModel;
import com.yangguang.huahui.mvp.presenter.PublishSupplyPresent;
import com.yangguang.huahui.mvp.presenter.UploadPresenter;
import com.yangguang.huahui.mvp.view.PublishView;
import com.yangguang.huahui.mvp.view.UploadView;
import com.yangguang.huahui.rx.RxManager;
import com.yangguang.huahui.rx.RxSubscriber;
import com.yangguang.huahui.ui.activitys.BaseActivity;
import com.yangguang.huahui.ui.activitys.InputActivity;
import com.yangguang.huahui.ui.adapters.GuigeAdapter;
import com.yangguang.huahui.ui.adapters.OnItemClickListener;
import com.yangguang.huahui.ui.adapters.PinzhongAdapter;
import com.yangguang.huahui.ui.adapters.ProvinceAdapter;
import com.yangguang.huahui.ui.adapters.SelectAdapter;
import com.yangguang.huahui.utils.CommonUtil;
import com.yangguang.huahui.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.stefan.pickturelib.Pickture;
import me.stefan.pickturelib.interf.OperateListenerAdapter;
import me.stefan.pickturelib.widget.PickRecyclerView;
import retrofit2.http.PUT;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2017/3/8.
 */

public class PublishSupplyFragment extends BaseMvpFragment<PublishView, PublishSupplyPresent> implements PublishView {
    BaseActivity baseActivity;
    @BindView(R.id.mRecyclerView)
    PickRecyclerView mRecyclerView;
    private ArrayList<String> selectedList = new ArrayList<>();
    private final int COLUMN = 3, MAX = 5;
    private Pickture mPickture;

    @BindView(R.id.tv_goods_type)
    TextView tv_goods_type;//商品分类
    @BindView(R.id.tv_variety)
    TextView tv_variety;//品种
    @BindView(R.id.tv_goods_name)
    TextView tv_goods_name;//商品名称
    @BindView(R.id.mLL_hide)
    LinearLayout mLL_hide;
    @BindView(R.id.tv_norm)
    TextView tv_norm;
    @BindView(R.id.tv_isHave)
    TextView tv_isHave;//是否现货
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.tv_source)
    TextView tv_source;
    @BindView(R.id.tv_method)
    TextView tv_method;//服务方式
    @BindView(R.id.tv_contact)
    TextView tv_contact;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_remarks)
    TextView tv_remarks;//补充说明

    private String supply_mark = "";//商品分类一级id
    private String variety = "";
    private String goods_type = "";
    private String goods_specifications = "";
    private String time_to_market = "";//上市时间
    private String expire_date = "";//下市时间
    private String service_method = "";//服务方式
    private String carousel = "";

    @OnClick({R.id.mLL_goods_type, R.id.mLL_isHave, R.id.mLL_price, R.id.mLL_source, R.id.mLL_method, R.id.mLL_contact,
            R.id.mLL_phone, R.id.btn_publish})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.mLL_goods_type:
                selectPinlei("商品分类");
                break;
            case R.id.mLL_isHave:
                selectGoods("是否现货");
                break;
            case R.id.mLL_price:
                startActivityForResult(new Intent(mActivity, InputActivity.class)
                        .putExtra("input_content", tv_price.getText().toString())
                        .putExtra("input_title", "商品价格")
                        .putExtra("input_length", 4)
                        .putExtra("edit_type", InputType.TYPE_CLASS_NUMBER)
                        .putExtra("input_type", 1), Config.INPUT_REQUEST_CODE);
                break;
            case R.id.mLL_source:
                selectAddress("发货地");
                break;
            case R.id.mLL_method:
                selectMethod("服务方式");
                break;
            case R.id.mLL_contact:
                startActivityForResult(new Intent(mActivity, InputActivity.class)
                        .putExtra("input_content", tv_contact.getText().toString())
                        .putExtra("input_title", "联系人")
                        .putExtra("input_length", 10)
                        .putExtra("input_type", 2), Config.INPUT_REQUEST_CODE);
                break;
            case R.id.mLL_phone:
                startActivityForResult(new Intent(mActivity, InputActivity.class)
                        .putExtra("input_content", tv_phone.getText().toString())
                        .putExtra("input_title", "手机号")
                        .putExtra("edit_type", 101)
                        .putExtra("input_type", 3), Config.INPUT_REQUEST_CODE);
                break;
            case R.id.btn_publish:
                submit();
                break;
        }
    }

    private void submit() {
        if (CommonUtil.isNull(variety)) {
            CommonUtil.myToastA(mActivity, "商品分类为空");
            return;
        }
        if (CommonUtil.isNull(tv_price.getText().toString())){
            CommonUtil.myToastA(mActivity, "商品价格为空");
            return;
        }
        if (CommonUtil.isNull(source_id)){
            CommonUtil.myToastA(mActivity, "发货地为空");
            return;
        }
        mPresenter.publish(DataInfo.TOKEN, goods_type, variety, goods_specifications, tv_goods_name.getText().toString(), source_id,
                tv_price.getText().toString(), tv_isHave.getText().toString(), time_to_market, expire_date, service_method, carousel,
                tv_contact.getText().toString(), tv_phone.getText().toString(), supply_mark, tv_remarks.getText().toString());
    }

    @Override
    protected int initLayoutId() {
        return R.layout.frag_publish_supply;
    }

    @Override
    protected void initView() {
        baseActivity = (BaseActivity) getActivity();
        baseActivity.getFlowers_type();
        baseActivity.getSelectData(3);
        mPickture = Pickture.with(mActivity).column(COLUMN).max(MAX).hasCamera(true).selected(selectedList);

        //当需要同步展示到 PickRecyclerView 需要同步基础参数给你的 mPickRecyclerView ，这个方法就是用于同步的
        mPickture.showOn(mRecyclerView);

        mRecyclerView.setOnOperateListener(new OperateListenerAdapter() {

            @Override
            public void onClickAdd() {
                //点击添加按钮
                mPickture.selected(selectedList).create();
            }

        });
    }

    @Override
    protected void initData() {
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            selectedList = data.getStringArrayListExtra(Pickture.PARAM_PICKRESULT);
            mRecyclerView.bind(selectedList);
            selectedList = mRecyclerView.getImageList();
            mPresenter.uploadFile(selectedList);
        }
        if (requestCode == Config.INPUT_REQUEST_CODE) {
            if (resultCode == Config.INPUT_RESULT_CODE) {
                switch (data.getIntExtra("input_type", 0)) {
                    case 1:
                        tv_price.setText(data.getStringExtra("input"));
                        break;
                    case 2:
                        tv_contact.setText(data.getStringExtra("input"));
                        break;
                    case 3:
                        tv_phone.setText(data.getStringExtra("input"));
                        break;
                }
            }
        }
    }

    @Override
    public void onSuccess(Upload upload) {
        for (String url : upload.getUrl()) {
            carousel += url + ",";
        }
        if (carousel.length() > 0) {
            carousel = carousel.substring(0, carousel.length() - 1);
        }
        LogUtil.e(carousel, true);
    }

    @Override
    public void onSuccess(BuyEditInfo buyEditInfo) {
    }

    @Override
    public void onSuccess(HttpResult httpResult) {
        CommonUtil.myToastA(mActivity, httpResult.getMsg());
        if (httpResult.getStatus() == 200){
            baseActivity.finish();
        }
    }

    @Override
    public void onError() {

    }

    private int fistPosition = -1;
    private int seconPosition = -1;
    private int thirdPosition = -1;
    private String yiji_id = "";
    private String erji_id = "";
    private String erji_name = "";
    private String sanji_id = "";
    private String sanji_name = "";

    private void selectPinlei(String title) {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.area_select, null);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_input_title);
        tv_title.setText(title);
        ListView lv_first = (ListView) contentView.findViewById(R.id.lv_first);
        ListView lv_second = (ListView) contentView.findViewById(R.id.lv_second);
        final ListView lv_third = (ListView) contentView.findViewById(R.id.lv_third);
        PinzhongAdapter pinzhongAdapter = new PinzhongAdapter(mActivity, baseActivity.flowersType.getList(), R.layout.select_area_list_item,
                lv_second, lv_third, fistPosition, seconPosition, thirdPosition);
        lv_first.setAdapter(pinzhongAdapter);
        final AlertDialog alertDialog = baseActivity.show_dialog_max(contentView);
        pinzhongAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                yiji_id = id;
            }
        });
        PinzhongAdapter.SecondAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                erji_id = id;
                erji_name = name;
                sanji_id = "";
                sanji_name = "";
                selectNorm("规格", id);
            }
        });
        PinzhongAdapter.SecondAdapter.ThirdAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                sanji_id = id;
                sanji_name = name;
            }
        });
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.iv_close:
                        alertDialog.dismiss();
                        break;
                    case R.id.iv_ok:
                        if (lv_third.getAdapter() != null
                                && CommonUtil.isNull(sanji_id)) {
                            CommonUtil.myToastA(mActivity, "请选择第三类");
                            return;
                        }

                        mLL_hide.setVisibility(View.VISIBLE);
                        tv_goods_type.setText(erji_name);
                        tv_variety.setText(sanji_name);
                        tv_goods_name.setText(sanji_name + " " + erji_name);
                        supply_mark = yiji_id;
                        goods_type = erji_id;
                        variety = sanji_id;
                        alertDialog.dismiss();
                        break;
                }
            }
        };
        contentView.findViewById(R.id.iv_close).setOnClickListener(listener);
        contentView.findViewById(R.id.iv_ok).setOnClickListener(listener);
    }

    private void selectNorm(final String title, String id) {
        RxManager.getInstance().doSubscribe(new CommonModel().getNorm(id), new RxSubscriber<Guige>(false) {
            @Override
            protected void _onNext(Guige guige) {
                View contentView = LayoutInflater.from(mActivity).inflate(R.layout.select_norm, null);
                TextView tv_title = (TextView) contentView.findViewById(R.id.tv_title);
                RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.mRecyclerView);
                tv_title.setText(title);
                List<SelectEntity> datas = new ArrayList<SelectEntity>();
                for (Guige.ListBean listBean : guige.getList()) {
                    if (listBean.getSubclass().size() > 0) {
                        SelectEntity entity = new SelectEntity();
                        entity.setId(listBean.getId());
                        entity.setName(listBean.getClassname());
                        entity.setItemType(1);
                        datas.add(entity);
                    }
                    for (Guige.ListBean.SubclassBean subclassBean : listBean.getSubclass()) {
                        SelectEntity suEntity = new SelectEntity();
                        suEntity.setId(subclassBean.getId());
                        suEntity.setName(subclassBean.getSelect_name());
                        suEntity.setItemType(2);
                        datas.add(suEntity);
                    }
                }
                GuigeAdapter adapter = new GuigeAdapter(datas);
                recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 3, GridLayoutManager.VERTICAL, false));
                recyclerView.setAdapter(adapter);
                if (datas.size() > 0) {
                    final AlertDialog alertDialog = baseActivity.show_dialog_max(contentView);
                    adapter.setOnItemClick(new GuigeAdapter.OnItemClick() {
                        @Override
                        public void onItemClick(int position, String id, String name) {
                            alertDialog.dismiss();
                            goods_specifications = id;
                            tv_norm.setText(name);
                        }
                    });
                } else {
                    goods_specifications = "";
                    tv_norm.setText("");
                }

            }

            @Override
            protected void _onError() {

            }
        });
    }

    String market_date_str = "";
    String expire_date_str = "";
    TextView tv_market_date;
    TextView tv_expire_date;

    private void selectGoods(String title) {
        final View contentView = LayoutInflater.from(mActivity).inflate(R.layout.xianhuo_select, null);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_title);
        tv_title.setText(title);
        final AlertDialog alertDialog = baseActivity.show_dialog_max(contentView);
        RadioGroup radioGroup = (RadioGroup) contentView.findViewById(R.id.radioGroup);
        final RadioButton rb_xianhuo = (RadioButton) contentView.findViewById(R.id.rb_xianhuo);
        tv_market_date = (TextView) contentView.findViewById(R.id.tv_market_date);
        tv_expire_date = (TextView) contentView.findViewById(R.id.tv_expire_date);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_xianhuo:
                        contentView.findViewById(R.id.mLL_market_date).setVisibility(View.VISIBLE);
                        break;
                    case R.id.rb_yushou:
                        contentView.findViewById(R.id.mLL_market_date).setVisibility(View.GONE);
                        break;
                }
            }
        });
        contentView.findViewById(R.id.mLL_market_date).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                market_date_str = dateAllDialog("上市时间", 1);
            }
        });
        contentView.findViewById(R.id.mLL_expire_date).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                expire_date_str = dateAllDialog("下市时间", 2);
            }
        });
        contentView.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (rb_xianhuo.isChecked()) {
                    tv_isHave.setText("现货");
                } else {
                    tv_isHave.setText("预售");
                }

                if (!CommonUtil.isNull(market_date_str)) {
                    time_to_market = CommonUtil.getMillisFromDate(market_date_str, "yyyy-MM-dd") + "";
                }
                if (!CommonUtil.isNull(expire_date_str)) {
                    expire_date = CommonUtil.getMillisFromDate(expire_date_str, "yyyy-MM-dd") + "";
                }
                alertDialog.dismiss();
            }
        });
    }

    private String select_date = "";

    private String dateAllDialog(String title, final int type) {
        final View contentView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_date_all, null);
        final AlertDialog alertDialog = baseActivity.show_bottom_dialog(contentView);
        CrossDatePicker datePicker = (CrossDatePicker) contentView.findViewById(R.id.wheel_str_date);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_input_title);
        tv_title.setText(title);
        datePicker.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolling(float deltaX, float deltaY) {

            }

            @Override
            public void onWheelSelected(int index, String data) {
                select_date = data;
            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });
        View.OnClickListener date_listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.iv_ok:
                        long select_millis = CommonUtil.getMillisFromDate(select_date, "yyyy-MM-dd");
                        alertDialog.dismiss();
                        if (type == 1) {
                            tv_market_date.setText(select_date);
                        } else if (type == 2) {
                            tv_expire_date.setText(select_date);
                            expire_date = CommonUtil.getMillisFromDate(select_date, "yyyy-MM-dd") + "";
                        }
                    case R.id.iv_close:
                        alertDialog.dismiss();
                        break;
                }
            }
        };
        contentView.findViewById(R.id.iv_close).setOnClickListener(date_listener);
        contentView.findViewById(R.id.iv_ok).setOnClickListener(date_listener);
        return select_date;
    }

    private int proPosition = -1;
    private int cityPostion = -1;
    private int areaPosition = -1;
    String source_id = "";
    String source_name = "";

    private void selectAddress(String title) {
        final List<String> list_id = new ArrayList<>();
        final List<String> list_name = new ArrayList<>();
        source_id = "";
        source_name = "";
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.area_select, null);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_input_title);
        tv_title.setText(title);
        ListView lv_first = (ListView) contentView.findViewById(R.id.lv_first);
        ListView lv_second = (ListView) contentView.findViewById(R.id.lv_second);
        ListView lv_third = (ListView) contentView.findViewById(R.id.lv_third);
        ProvinceAdapter provinceAdapter = new ProvinceAdapter(mActivity, baseActivity.mArea.getList(), R.layout.select_area_list_item,
                lv_second, lv_third, proPosition, cityPostion, areaPosition);
        provinceAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                fistPosition = position;
                if (!CommonUtil.isNull(id)) {
                    if (list_id.size() > 0) {
                        list_id.removeAll(list_id);
                    }
                    list_id.add(id);
                }
                if (!CommonUtil.isNull(name)) {
                    if (list_name.size() > 0) {
                        list_name.removeAll(list_name);
                    }
                    list_name.add(name);
                }
            }
        });
        ProvinceAdapter.CityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                seconPosition = position;
                if (!CommonUtil.isNull(id)) {
                    if (list_id.size() == 2) {
                        list_id.remove(1);
                    } else if (list_id.size() == 3) {
                        list_id.remove(1);
                        list_id.remove(1);
                    }
                    list_id.add(id);
                }
                if (!CommonUtil.isNull(name)) {
                    if (list_name.size() == 2) {
                        list_name.remove(1);
                    } else if (list_name.size() == 3) {
                        list_name.remove(1);
                        list_name.remove(1);
                    }
                    list_name.add(name);
                }
            }
        });
        ProvinceAdapter.CityAdapter.AreaAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                thirdPosition = position;
                if (!CommonUtil.isNull(id)) {
                    if (list_id.size() == 3) {
                        list_id.remove(2);
                    }
                    list_id.add(id);
                }
                if (!CommonUtil.isNull(name)) {
                    if (list_name.size() == 3) {
                        list_name.remove(2);
                    }
                    list_name.add(name);
                }
            }
        });
        lv_first.setAdapter(provinceAdapter);
        baseActivity.show_dialog_max(contentView, mActivity);
        View.OnClickListener areaListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.iv_close:
                        baseActivity.alertDialog.dismiss();
                        break;
                    case R.id.iv_ok:
                        for (String name : list_name) {
                            source_name += name + "-";
                        }
                        if (source_name.length() > 0) {
                            source_name = source_name.substring(0, source_name.length() - 1);
                        }
                        tv_source.setText(source_name);
                        for (String name : list_id) {
                            source_id += name + ",";
                        }
                        if (source_id.length() > 0) {
                            source_id = source_id.substring(0, source_id.length() - 1);
                        }
                        baseActivity.alertDialog.dismiss();
                        break;
                }
            }
        };
        contentView.findViewById(R.id.iv_close).setOnClickListener(areaListener);
        contentView.findViewById(R.id.iv_ok).setOnClickListener(areaListener);
    }

    /**
     * 服务方式
     * @param title
     */
    private void selectMethod(String title){
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_list, null);
        ListView mListView = (ListView) contentView.findViewById(R.id.mListView);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_title);
        tv_title.setText(title);
        SelectAdapter selectAdapter = new SelectAdapter(mActivity, baseActivity.identity_datas, R.layout.select_list_item, new SelectAdapter.OnClickCallback() {
            @Override
            public void callBack(String id, String name) {
                tv_method.setText(name);
                service_method = id;
                baseActivity.alertDialog.dismiss();
            }
        });
        mListView.setAdapter(selectAdapter);
        baseActivity.show_bottom_dialog(contentView);
    }

    @Override
    protected PublishSupplyPresent initPresenter() {
        return new PublishSupplyPresent();
    }

    @Override
    protected void fetchData() {

    }
}
